// 获取类别
function renderCategory() {
  axios.get('/my/category/list').then(res => {
    let { status, data } = res.data;
    if (status === 0) {
      let arr = [];
      data.forEach(item => {
        arr.push(
          `<tr>
          <td>${item.name}</td>
          <td>${item.alias}</td>
          <td>
            <button type="button" class="layui-btn layui-btn-xs edit" data-id="${item.id}" data-name="${item.name}" data-alias="${item.alias}">编辑</button>
            <button type="button" data-id=${item.id} class="del dislodge layui-btn layui-btn-xs layui-btn-danger">删除</button>
          </td>
        </tr>  

        `)
      });
      $('tbody').html(arr.join(''))
    }
  })
}
renderCategory();

// 添加类别

var addIndex;

$('.accretion').on('click',function () {
  addIndex = layer.open( {
    type:1,
    title: '添加类别',
    content: $('#tpl-add').html(),
    area: ['500px', '300px']
  })
})

$('body').on('submit','#add-form',function (e) {
  e.preventDefault();
  let data = $(this).serialize();
  axios.post('/my/category/add',data).then(res => {
    let {status,message} = res.data;
    if(status === 0) {
      layer.msg(message);
      renderCategory();
    }
    layer.close(addIndex);
  })
});

// 删除分类
$('tbody').on('click','.dislodge',function() {
  
  var id = $(this).data('id');
  layer.confirm('你是否删除?',function (index) {
    console.log(id);
    axios.get (`/my/category/delete?id=${id}`).then(res => {
      let {status,message} = res.data;
      if (status === 0) {
        layer.msg(message);
        renderCategory();
      }

    })
    layer.close(index);
  })
})

// 编辑分类
// var editIndex;


$('body').on('click','button:contains("编辑")',function () {
  var information = $(this).data();
  console.log(information);
  editIndex = layer.open( {
    type:1,
    title: '编辑分类',
    content: $('#tpl-edit').html(),
    area: ['500px', '300px'],
    success: function () {
      console.log($('#edit-form '));
      $('#edit-form input[name="name"]').val(information.name);
      $('#edit-form input[name="alias"]').val(information.alias);
      $('#edit-form input[name="id"]').val(information.id);
    }
  })
})

$('body').on('submit','#edit-form',function(e) {
  e.preventDefault();
  var data = $(this).serialize();
  axios.post('/my/category/update',data).then (res => {
    let {status,message} = res.data;
    if(status === 0) {
      layer.msg(message);
      renderCategory();
      layer.close(editIndex)
    }
  })
})